package leetcode

import kotlinetc.println

//https://leetcode.com/problems/spiral-matrix/

/**
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
 */
fun main(args: Array<String>) {

    spiralOrder(arrayOf(
            intArrayOf(1, 2, 3, 4)

    )).println()
}

fun spiralOrder(matrix: Array<IntArray>): List<Int> {

    if (matrix.isEmpty())return listOf()
    val m = matrix.size
    val n = matrix[0].size

    val result = ArrayList<Int>()


    var l = 0
    var r = n - 1
    var t = 0
    var b = m - 1
    val cycleTime = (Math.min(m, n) + 1) / 2 //

    for (i in 0 until cycleTime) {
        //----------->
        val arr = matrix[t]

        var j = l
        while (j <= r) {
            result.add(arr[j])
            j++
        }
        j--

        //top to bottom
        var k = t + 1
        while (k <= b) {
            result.add(matrix[k][j])
            k++
        }

        var p = j - 1
        while (p >= l && b > t) {
            result.add(matrix[b][p])
            p--
        }

        //bottom to top

        k = b - 1
        while (k > t && l < r) {
            result.add(matrix[k][l])
            k--
        }

        l++
        r--
        t++
        b--

    }
    return result
}